package com.hhd.flow.engine.cmd.impl;

//import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.hhd.flow.engine.utils.CommonUtils;
import com.hhd.flow.entity.FlowProcessInstance;
import com.hhd.flow.entity.FlowUserTask;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;

import java.util.List;
import java.util.stream.Collectors;

@Setter
@Getter
@SuperBuilder(toBuilder = true)
public abstract class FlowUserTaskChangeCommand<T> extends AutoCompleteCommand<T> {
    private List<String> beforeChangeFlowUserTaskIds = CommonUtils.newList();

    public void beforeChangeFlowUserTask(FlowProcessInstance flowProcessInstance) {
        beforeChangeFlowUserTaskIds = getEngine().getFlowUserTaskService().lambdaQuery()
                .eq(FlowUserTask::getProcessInstanceId, flowProcessInstance.getId())
                .select(FlowUserTask::getId).list()
                .stream().map(FlowUserTask::getId).collect(Collectors.toList());
    }

    public void afterChangeFlowUserTask(FlowProcessInstance flowProcessInstance) {
        LambdaQueryChainWrapper<FlowUserTask> query = getEngine().getFlowUserTaskService().lambdaQuery()
                .eq(FlowUserTask::getProcessInstanceId, flowProcessInstance.getId());
        if (!CommonUtils.isEmpty(beforeChangeFlowUserTaskIds)) {
            query.notIn(FlowUserTask::getId, beforeChangeFlowUserTaskIds);
        }
        List<FlowUserTask> flowUserTasks = query.list();

        if (!CommonUtils.isEmpty(flowUserTasks)) {
            publishCreateUserTaskEvent(flowUserTasks, flowProcessInstance);
        }
    }
}
